package adv12;

//2：baidu 一个线程死锁的例子
public class Work {
    public static void main(String[] args) {
        Resource r1 = new Resource();
        Resource r2 = new Resource();
        Thread1 t1 = new Thread1(r1, r2);
        Thread2 t2 = new Thread2(r1, r2);
        t1.start();
        t2.start();
    }
}

class Resource {
    private int i = 1;
}

class Thread1 extends Thread {
    Resource r1, r2;

    public Thread1(Resource r1, Resource r2) {
        this.r1 = r1;
        this.r2 = r2;
    }

    public void run() {
        while (true) {
            synchronized (r1) {
                System.out.println("线程1获取r1的锁。");
                synchronized (r2) {
                    System.out.println("线程1获取r2的锁。");
                }
            }
        }
    }
}

class Thread2 extends Thread {
    Resource r1, r2;

    public Thread2(Resource r1, Resource r2) {
        this.r1 = r1;
        this.r2 = r2;
    }

    public void run() {
        while (true) {
            synchronized (r2) {
                System.out.println("线程2获取r2的锁。");
                synchronized (r1) {
                    System.out.println("线程2获取r1的锁。");
                }
            }
        }
    }
}

